package info.cs52.fes.prolog;

import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

/**
 * Lấy thông tin dự báo thời tiết từ trung tâm dự báo khí tượng thuỷ văn trung
 * ương Việt Nam.
 * 
 * @author cumeo89
 * 
 */
public class WeatherForecastLoader {

	private static final Pattern CURRENT_TEMP = Pattern.compile(
			Pattern.quote("<td class=\"forecast_detail\" align=\"left\"><strong>") + 
			"\\s*(\\d+)\\s*" + 
			Pattern.quote("<sup>o</sup>C</strong></td>"));
	
	private static final Pattern NEXT_TEMP = Pattern.compile(
			Pattern.quote("<td class=\"tieude_dubao_yeuto_content\" align=\"center\"><strong>") +
			"\\s*(\\d+)\\s*" +
			Pattern.quote("</strong>"));

	public int getCurrentTemperature() throws IOException {
		String url = "http://www.nchmf.gov.vn/web/vi-VN/62/19/58/map/Default.aspx";
		String str = IOUtils.toString(new URL(url).openStream(), "UTF-8");
		
		Matcher matcher = CURRENT_TEMP.matcher(str);
		if (!matcher.find()) {
			return -1;
		} 
		return Integer.parseInt(matcher.group(1));
	}
	
	/**
	 * TODO get weather types
	 * @return
	 * @throws IOException 
	 */
	public WeatherForecast[] loadForecasts() throws IOException {
		String url = "http://www.nchmf.gov.vn/web/vi-VN/62/19/58/map/Default.aspx";
		String str = IOUtils.toString(new URL(url).openStream(), "UTF-8");

		int[] mins = new int[3];
		int[] maxs = new int[3];
		Matcher matcher = NEXT_TEMP.matcher(str);
		for (int i = 0; i < 3; i++) {
			if (!matcher.find()) {
				return null;
			}
			mins[i] = Integer.parseInt(matcher.group(1));
		}
		for (int i = 0; i < 3; i++) {
			if (!matcher.find()) {
				return null;
			}
			maxs[i] = Integer.parseInt(matcher.group(1));
		}

		WeatherForecast[] forecasts = new WeatherForecast[4];
		for (int i = 0; i < 3; i++) {
			forecasts[i] = new WeatherForecast(mins[i], maxs[i], null);
		}
		return forecasts;
	}

}
